package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.authority.dao.AppSqlConfig;
import com.cssy.authority.service.IAuthorityService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.authority.service.impl.AuthorityServiceImpl;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutItemDO;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.entity.LogicSalesItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionStorageOutService;
import com.cssy.xxkj.logic.service.ILogicSalesService;
import com.cssy.xxkj.logic.service.ILogicWarehouseInventoryService;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
/**
 * 销售出库
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/prostorageout")
public class ProductionStorageOutController extends BaseController<LogicProductionStorageoutDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionStorageOutController.class);

	private static final String MANAGER = "/xxkj/logic/prostorageout/ProStorageOutManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/prostorageout/ProStorageOutOperation";// 添加、修改、显示页面
	
	
	@Resource(name = "logicProductionStorageOutService")
	private ILogicProductionStorageOutService logicProductionStorageOutService;
	
	@Resource(name = "logicWarehouseInventoryService")
	private ILogicWarehouseInventoryService logicWarehouseInventoryService;
	
	@Resource(name = "logicSalesService")
	private ILogicSalesService logicSalesService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Resource(name= "oftenMapUtil")
	private OftenMapUtil oftenMapUtil;
	
	@Resource(name= "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "zd011BillStatus", BillStatusUtil.PROSTOROUT_STATUS_FIVE);
		scs.setOrderBy("bizCreatorDate desc");
		Map<String, Object> whMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService, "zd004WhCode");
		scs.addCondition(whMap.get("option")+"",(List<String>)whMap.get("roleWhList"));
		SearchResult result = logicProductionStorageOutService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicProductionStorageoutDO storageout = logicProductionStorageOutService.findListById(id);
			if(StringUtils.isNotBlank(storageout.getZd003PiCode())){
				SearchConditions scs = new SearchConditions();
				scs.setRemovedProperty(null);
				scs.addCondition("zd002PiCode", storageout.getZd003PiCode(), SearchCondition.OP_EQUAL);
				List<LogicSalesDO> planList = logicSalesService.findListByExample(scs).getResults();
				if(planList==null||planList.isEmpty()||planList.size()==0){
					model.addAttribute("xilie", "");
				}else{
					String xilie="";
					if(planList.get(0).getZd028SaleType().equals("BT")){
						xilie="套床";
					}else if(planList.get(0).getZd028SaleType().equals("MT")){
						xilie="床垫";
					}
					model.addAttribute("xilie", xilie);
				}
				if(storageout!=null&&StringUtils.isNotBlank(storageout.getZd006Aegnt())){
					SqlMapClient sqlMapClient = AppSqlConfig.getSqlMapInstance();
					IAuthorityService ias = new AuthorityServiceImpl(sqlMapClient);
					com.cssy.authority.entity.User u = ias.getByUserName(storageout.getZd006Aegnt());
					model.addAttribute("userName", u.getRealname());
				}

				
			}
			model.addAttribute("storageout", storageout);
			if (storageout.getZd011BillStatus().equals(BillStatusUtil.PROSTOROUT_STATUS_ONE)||storageout.getZd011BillStatus().equals(BillStatusUtil.PROSTOROUT_STATUS_SIX)){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (storageout.getZd011BillStatus().equals(BillStatusUtil.PROSTOROUT_STATUS_FIVE)){
				model.addAttribute("viewflag", "tongguo");
			}
			if (storageout.getZd011BillStatus().equals(BillStatusUtil.PROSTOROUT_STATUS_TWO)){
				model.addAttribute("viewflag", "shenpi");
			}
			if(storageout!=null&&StringUtils.isNotBlank(storageout.getZd006Aegnt())){
				SqlMapClient sqlMapClient = AppSqlConfig.getSqlMapInstance();
				IAuthorityService ias = new AuthorityServiceImpl(sqlMapClient);
				com.cssy.authority.entity.User u = ias.getByUserName(storageout.getZd006Aegnt());
				model.addAttribute("userName", u.getRealname());
			}
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionStorageoutDO prodispat = logicProductionStorageOutService.findListById(id);
			List<LogicProductionStorageoutItemDO> soitem = logicProductionStorageOutService.findStorOutItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionStorageoutDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("addressInfos");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionStorageOutService.outSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionStorageoutDO ld = logicProductionStorageOutService.findListById(field);
				logicProductionStorageOutService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/gridBomItems")
	public void gridBomItems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		String whcode =request.getParameter("whcode");
		if(StringUtils.isNotBlank(id)){
			List<LogicProductionStorageoutItemDO> inList = new ArrayList<LogicProductionStorageoutItemDO>();
			LogicSalesDO sales = logicSalesService.findListById(id);
			List<LogicSalesItemDO> salesitem = logicSalesService.findSalesItemList(sales.getId());
			if(salesitem!=null&&!salesitem.isEmpty()&&salesitem.size()>0){
				inList=this.salesToStorageOut(salesitem,sales,whcode );
			}//增加 自己添加的物品 注意
			Map<String, LogicProductionStorageoutItemDO> itemMap=new HashMap<String, LogicProductionStorageoutItemDO>();
			for(LogicProductionStorageoutItemDO item:inList){
				//code name model spec color quanlity picode
				String key=(StringUtils.isEmpty(item.getZd002MaterialsCode())?null:item.getZd002MaterialsCode())+"_"+
							(StringUtils.isEmpty(item.getZd002MaterialsName())?null:item.getZd002MaterialsName())+"_"+
							(StringUtils.isEmpty(item.getZd004MaterialsModel())?null:item.getZd004MaterialsModel())+"_"+
							(StringUtils.isEmpty(item.getZd016MaterialsSize())?null:item.getZd016MaterialsSize())+"_"+
							(StringUtils.isEmpty(item.getZd017MaterialsColor())?null:item.getZd017MaterialsColor())+"_"+
							(StringUtils.isEmpty(item.getZd018MaterialsQuality())?null:item.getZd018MaterialsQuality())+"_"+
							(StringUtils.isEmpty(item.getZd024Picode())?null:item.getZd024Picode());
				itemMap.put(key, item);
			}
			Map<String, Object> paramMap= new HashMap<String, Object>();
			paramMap.put("oriCode", sales.getZd001FormCode());
			paramMap.put("billSt", BillStatusUtil.PROSTOROUT_STATUS_FIVE);
			List<LogicProductionStorageoutItemDO> listItem=this.logicProductionStorageOutService.findStorOutItemListByMap(paramMap);
			for(LogicProductionStorageoutItemDO item:listItem){
				//code name model spec color quanlity picode
				String key=(StringUtils.isEmpty(item.getZd002MaterialsCode())?null:item.getZd002MaterialsCode())+"_"+
							(StringUtils.isEmpty(item.getZd002MaterialsName())?null:item.getZd002MaterialsName())+"_"+
							(StringUtils.isEmpty(item.getZd004MaterialsModel())?null:item.getZd004MaterialsModel())+"_"+
							(StringUtils.isEmpty(item.getZd016MaterialsSize())?null:item.getZd016MaterialsSize())+"_"+
							(StringUtils.isEmpty(item.getZd017MaterialsColor())?null:item.getZd017MaterialsColor())+"_"+
							(StringUtils.isEmpty(item.getZd018MaterialsQuality())?null:item.getZd018MaterialsQuality())+"_"+
							(StringUtils.isEmpty(item.getZd024Picode())?null:item.getZd024Picode());
				LogicProductionStorageoutItemDO it=itemMap.get(key);
				if(it==null){
					item.setZd020WareOutQuanlity(item.getZd007Quantity().subtract(
							item.getZd007BackQuantity()==null?BigDecimal.ZERO:item.getZd007BackQuantity()));
					item.setZd007Quantity(item.getZd021SalesQuanlity().subtract(item.getZd020WareOutQuanlity()));
					inList.add(item);
				}
			}
			OutJsonGrid out = new OutJsonGrid(inList);
			out.printJSon(response);
		}
	}

	
	
	private List<LogicProductionStorageoutItemDO> salesToStorageOut(List<LogicSalesItemDO> salesitem,LogicSalesDO sales,String whcode) throws Exception{
		List<LogicProductionStorageoutItemDO> outList = new ArrayList<LogicProductionStorageoutItemDO>();
		//List<LogicProductionStorageoutItemDO> inListy=this.listItem(sales.getZd001FormCode(), sales.getZd002PiCode());
		Map<String, BigDecimal> sgeQuantityMap = logicWarehouseInventoryService.getStorageQuaitityToMap(sales.getZd002PiCode(), whcode, null, "BC");
		Map<String, BigDecimal> hasOutQuantityMap = this.findQueryHasStorageoutItemToMap(sales.getZd001FormCode(), sales.getZd002PiCode(), whcode);
		for(int i=0;i<salesitem.size();i++){
			LogicSalesItemDO saleItem = salesitem.get(i);
			if(saleItem==null||StringUtils.isBlank(saleItem.getId())){
				continue;
			}
			//pi 仓库编码   code name spec model  quanlity color
			String keyStr=(StringUtils.isEmpty(sales.getZd002PiCode())?null:sales.getZd002PiCode())+"_"+
						(StringUtils.isEmpty(whcode)?null:whcode)+"_"+
						(StringUtils.isEmpty(saleItem.getZd007MaterialsCode())?null:saleItem.getZd007MaterialsCode())+"_"+
						(StringUtils.isEmpty(saleItem.getZd008MaterialsName())?null:saleItem.getZd008MaterialsName())+"_"+
						(StringUtils.isEmpty(saleItem.getZd038MaterialsSize())?null:saleItem.getZd038MaterialsSize())+"_"+
						(StringUtils.isEmpty(saleItem.getZd010MaterialsModel())?null:saleItem.getZd010MaterialsModel())+"_"+
						(StringUtils.isEmpty(saleItem.getZd042MaterialsQuality())?null:saleItem.getZd042MaterialsQuality())+"_"+
						(StringUtils.isEmpty(saleItem.getZd041MaterialsColor())?null:saleItem.getZd041MaterialsColor());
			LogicProductionStorageoutItemDO inItem = new LogicProductionStorageoutItemDO();
			inItem.setZd002MaterialsCode(saleItem.getZd007MaterialsCode());
			inItem.setZd002MaterialsId(saleItem.getZd006MaterialsId());
			inItem.setZd002MaterialsName(saleItem.getZd008MaterialsName());
			inItem.setZd003MaterialsSpec(saleItem.getZd011MaterialsSpec());
			inItem.setZd004MaterialsModel(saleItem.getZd010MaterialsModel());
			inItem.setZd006Unit(saleItem.getZd012MaterialsUnit());
			inItem.setZd009Price(saleItem.getZd017Price());
			inItem.setZd015MaterialsDescription(saleItem.getZd036MaterialsDescription());
			inItem.setZd016MaterialsSize(saleItem.getZd038MaterialsSize());
			inItem.setZd017MaterialsColor(saleItem.getZd041MaterialsColor());
			inItem.setZd018MaterialsQuality(saleItem.getZd042MaterialsQuality());
			inItem.setZd021SalesQuanlity(saleItem.getZd013Quantity());
			inItem.setZd024Picode(sales.getZd002PiCode());
			if(sgeQuantityMap==null||sgeQuantityMap.get(keyStr)==null){
				inItem.setZd019WhQuanlity(BigDecimal.ZERO);
			}else{
				inItem.setZd019WhQuanlity(sgeQuantityMap.get(keyStr));
			}
			//可以出库的库存
			BigDecimal sumQuantity = saleItem.getZd013Quantity()==null?BigDecimal.ZERO:saleItem.getZd013Quantity();
			if(hasOutQuantityMap==null||hasOutQuantityMap.get(keyStr)==null){
				inItem.setZd020WareOutQuanlity(BigDecimal.ZERO);
				inItem.setZd007Quantity(sumQuantity);
			}else{
				inItem.setZd020WareOutQuanlity(hasOutQuantityMap.get(keyStr));
				inItem.setZd007Quantity(sumQuantity.subtract(hasOutQuantityMap.get(keyStr)));
			}
			/*inItem.setZd020WareOutQuanlity(this.getProductionQuantity(inListy, salesitem.get(i).getZd007MaterialsCode()));
			if(inItem.getZd020WareOutQuanlity().compareTo(new BigDecimal(0.0))==1){
				BigDecimal bg =MathUtil.mathUtil.subtract(saleItem.getZd013Quantity(), inItem.getZd020WareOutQuanlity());
				inItem.setZd007Quantity(bg);
			}else{
				inItem.setZd007Quantity(saleItem.getZd013Quantity());
			}*/
			outList.add(inItem);
		}
		return outList;
	}
	/**
	 * 查询当前已出库的产品
	 */
	
	private Map<String, BigDecimal> findQueryHasStorageoutItemToMap(String oriCode, String piCode, String whCode)throws Exception{
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("piCode", piCode);
		paramMap.put("oriCode", oriCode);
		paramMap.put("whCode", whCode);
		paramMap.put("billSt", BillStatusUtil.PROSTOROUT_STATUS_FIVE);
		return logicProductionStorageOutService.findStorageoutItemToMap(paramMap);
	}
	
	
	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String,String> map=new HashMap<String,String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicProductionStorageoutDO lot=logicProductionStorageOutService.findListById(ids);
				if(lot.getId()!=null){
					lot.setZd011BillStatus(BillStatusUtil.PROSTOROUT_STATUS_SIX);
					logicProductionStorageOutService.update(lot, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
	
}
